const express = require('express')
    // 创建路由对象
const router = express.Router()

// 1. 导入验证表单数据的中间件
const expressJoi = require('@escook/express-joi')
    // 2. 导入需要的验证规则对象
const { reg_login_schema } = require('../schema/user')


//导入数据库操作模块
const db = require('../db/index')
    //获取用户信息
router.get('/user', (req, res) => {
    const sql = `select * from users where phone=?`
    db.query(sql, req.user.phone, function(err, results) {
        if (err) return res.cc(err)
        res.send({
            status: 200,
            message: "获取用户信息成功",
            data: results[0]
        })
    })
})


//获取用户信息
router.get('/userId/:id', (req, res) => {
    const sql = `select * from users where id=?`
    db.query(sql, req.params.id, function(err, results) {
        if (err) return res.cc(err)
        res.send({
            status: 200,
            message: "获取用户信息成功",
            data: results[0]
        })
    })
})

//修改用户信息
router.put('/userinfo', expressJoi(reg_login_schema), (req, res) => {
    const sql = `update users set phone=${req.body.phone},username='${req.body.username}',
    password='${req.body.password}' where id =${req.user.id}`
    db.query(sql, req.user.phone, function(err, results) {
        if (err) return res.cc(err)
        res.send({
            status: 200,
            message: "修改用户信息成功"
        })
    })
})

//修改用户信息
router.put('/users/:id', expressJoi(reg_login_schema), (req, res) => {
    const sql = `update users set phone=${req.body.phone},username='${req.body.username}',
    password='${req.body.password}' where id =${req.params.id}`
    db.query(sql, function(err, results) {
        if (err) return res.cc(err)
        res.send({
            status: 200,
            message: "修改用户信息成功"
        })
    })
})

//获取全部用户
router.get('/userall', (req, res) => {
    const sql = 'select * from users'
    db.query(sql, req.user.phone, function(err, results) {
        if (err) return res.cc(err)
        res.send({
            status: 200,
            message: "获取用户信息成功",
            data: results
        })
    })
})

//获取根据名字获取
router.get('/userByName', (req, res) => {
    const sql = `select * from users where  username like '%${req.query.query}%'`
    db.query(sql, function(err, results) {
        if (err) return res.cc(err)
        res.send({
            status: 200,
            message: "获取用户信息成功",
            data: results
        })
    })
})

//根据ID删除用户
router.delete('/user/:id', (req, res) => {
    const sql = `delete from users where id = ${req.params.id}`
    db.query(sql, function(err, results) {
        if (err) return res.cc(err)
        res.send({
            status: 200,
            message: "删除用户信息成功",
        })
    })
})


// 将路由对象共享出去
module.exports = router